import React from 'react';
import { Spin, Button, Empty, Table, message, Select, Input, Radio, Modal, Tag } from 'antd';
import { ShareAltOutlined } from '@ant-design/icons';
import type { TablePaginationConfig } from 'antd/es/table';
import { fetchJacgDbTablePage, fetchDistinctTables, fetchTableSummaryPage, fetchTableOperations } from '../../../services/database';
import { queryCallGraph } from '../../../services/callGraphService';
import { buildFileLink, formatRelativePath as formatRelativePathUtil } from '../../../utils/gitUrlUtils';
import CallGraphViewer from '../CallGraphTab/CallGraphViewer';

interface DatabaseAnalysisProps {
    unitId: string;
    unitInfo?: any;
}

const DatabaseAnalysis: React.FC<DatabaseAnalysisProps> = ({ unitId, unitInfo }) => {
    // 操作视图状态
    const [loading, setLoading] = React.useState(false);
    const [records, setRecords] = React.useState<any[]>([]);
    const [pagination, setPagination] = React.useState<TablePaginationConfig>({ current: 1, pageSize: 10, total: 0 });

    // 表视图状态
    const [groupLoading, setGroupLoading] = React.useState(false);
    const [groupData, setGroupData] = React.useState<any[]>([]);
    const [groupTotal, setGroupTotal] = React.useState<number>(0);
    const [groupPageSize, setGroupPageSize] = React.useState<number>(10);
    const [groupCurrentPage, setGroupCurrentPage] = React.useState<number>(1);
    const [expandedRowKeys, setExpandedRowKeys] = React.useState<string[]>([]);
    const [expandedDataCache, setExpandedDataCache] = React.useState<Record<string, any[]>>({});

    // 通用筛选状态
    const [keyword, setKeyword] = React.useState<string>('');
    const [operationType, setOperationType] = React.useState<string | undefined>(undefined);
    const [viewMode, setViewMode] = React.useState<'table' | 'group'>('group'); // 'group' = 表视图, 'table' = 操作视图

    // 调用图弹窗相关状态
    const [callGraphModalVisible, setCallGraphModalVisible] = React.useState(false);
    const [callGraphData, setCallGraphData] = React.useState<any>(null);
    const [callGraphLoading, setCallGraphLoading] = React.useState(false);
    const [currentTableName, setCurrentTableName] = React.useState<string>('');

    // 删除表名下拉建议相关逻辑，简化操作视图

    // 加载操作视图数据（简化版）
    const loadPage = React.useCallback(async (pageNo?: number, pageSize?: number) => {
        if (!unitId) return;
        setLoading(true);
        try {
            const resp: any = await fetchJacgDbTablePage(unitId, {
                pageNum: pageNo || pagination.current || 1,
                pageSize: pageSize || pagination.pageSize || 10,
                keyword: keyword || undefined,
                operationType: operationType || undefined
            });
            const pageData = resp?.data || resp;
            const recs = pageData?.records || [];
            setRecords(recs);
            setPagination({
                current: pageData?.current || pageNo || 1,
                pageSize: pageData?.size || pageSize || 10,
                total: pageData?.total || 0,
                showSizeChanger: true
            });
        } catch (e) {
            setRecords([]);
            setPagination(p => ({ ...p, total: 0 }));
        } finally {
            setLoading(false);
        }
    }, [unitId, keyword, operationType, pagination.current, pagination.pageSize]);

    // 加载表视图数据（按表维度）
    const loadGroupData = React.useCallback(async (pageNo?: number, pageSize?: number) => {
        if (!unitId) return;
        setGroupLoading(true);
        try {
            const resp: any = await fetchTableSummaryPage(unitId, {
                pageNum: pageNo || groupCurrentPage,
                pageSize: pageSize || groupPageSize,
                keyword: keyword || undefined,
                operationType: operationType || undefined
            });
            const pageData = resp?.data || resp;
            const recs = pageData?.records || [];

            // 处理operationTypes字符串转数组
            const processedRecs = recs.map((rec: any) => ({
                ...rec,
                operationTypes: typeof rec.operationTypes === 'string'
                    ? rec.operationTypes.split(',').filter(Boolean)
                    : (rec.operationTypes || []),
                sourceTypes: typeof rec.sourceTypes === 'string'
                    ? rec.sourceTypes.split(',').filter(Boolean)
                    : (rec.sourceTypes || [])
            }));

            setGroupData(processedRecs);
            setGroupTotal(pageData?.total || 0);
            setGroupCurrentPage(pageData?.current || pageNo || 1);
        } catch (e) {
            setGroupData([]);
            setGroupTotal(0);
        } finally {
            setGroupLoading(false);
        }
    }, [unitId, groupCurrentPage, groupPageSize, keyword, operationType]);

    // 加载指定表的操作详情
    const loadTableOperations = React.useCallback(async (tableName: string) => {
        if (!unitId || !tableName) return;

        // 如果已缓存，直接返回
        if (expandedDataCache[tableName]) {
            return;
        }

        try {
            const resp: any = await fetchTableOperations(unitId, tableName, {
                pageNum: 1,
                pageSize: 100, // 一次加载较多数据
                operationType: operationType || undefined
            });
            const pageData = resp?.data || resp;
            const operations = pageData?.records || [];

            setExpandedDataCache(prev => ({
                ...prev,
                [tableName]: operations
            }));
        } catch (e) {
            console.error('加载表操作详情失败:', e);
        }
    }, [unitId, operationType, expandedDataCache]);

    React.useEffect(() => {
        // 初始加载
        if (viewMode === 'table') {
            loadPage(1, pagination.pageSize);
        } else {
            loadGroupData(1, groupPageSize);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [unitId, viewMode]);

    const onSearch = () => {
        if (viewMode === 'table') {
            loadPage(1, pagination.pageSize);
        } else {
            loadGroupData(1, groupPageSize);
            // 清空展开缓存
            setExpandedDataCache({});
            setExpandedRowKeys([]);
        }
    };

    const columns: any[] = [
        {
            title: '表',
            dataIndex: 'tableName',
            key: 'tableName',
            width: 180,
            ellipsis: true,
            render: (text: string) => (
                <span title={text}>{text}</span>
            )
        },
        {
            title: '操作',
            dataIndex: 'operationType',
            key: 'operationType',
            width: 100,
            ellipsis: true,
            render: (text: string, record: any) => {
                const operation = (text || record.operation || '').toUpperCase();
                if (!operation) return null;

                const operationColorMap: Record<string, string> = {
                    'SELECT': '#1890ff',
                    'INSERT': '#52c41a',
                    'UPDATE': '#faad14',
                    'DELETE': '#ff4d4f'
                };

                const color = operationColorMap[operation] || '#8c8c8c';

                return (
                    <Tag color={color} style={{ margin: 0, fontWeight: 600 }}>
                        {operation}
                    </Tag>
                );
            }
        },
        {
            title: '来源',
            dataIndex: 'sourceType',
            key: 'sourceType',
            width: 120,
            ellipsis: true,
            render: (text: string) => {
                if (!text) return null;

                const sourceTypeMap: Record<string, { label: string; color: string }> = {
                    'MYBATIS_XML': { label: 'XML', color: '#1890ff' },
                    'MYBATIS_ANNOTATION': { label: '注解', color: '#722ed1' },
                    'JPA': { label: 'JPA', color: '#faad14' },
                    'NATIVE': { label: '原生', color: '#13c2c2' }
                };

                const config = sourceTypeMap[text] || { label: text.toUpperCase(), color: '#8c8c8c' };

                return (
                    <Tag color={config.color} style={{ margin: 0 }}>
                        {config.label.toUpperCase()}
                    </Tag>
                );
            }
        },
        {
            title: '包名',
            dataIndex: 'mapperClassName',
            key: 'packageName',
            width: 250,
            ellipsis: true,
            render: (text: string) => {
                if (!text) return null;

                // 提取包名（去掉最后的类名）
                const parts = text.split('.');
                if (parts.length <= 1) return null;

                const packageName = parts.slice(0, -1).join('.');

                return (
                    <span
                        style={{
                            fontSize: '12px',
                            color: '#8c8c8c',
                            fontFamily: 'Consolas, Monaco, monospace'
                        }}
                        title={packageName}
                    >
                        {packageName}
                    </span>
                );
            }
        },
        {
            title: '类',
            dataIndex: 'mapperClassName',
            key: 'mapperClassName',
            width: 180,
            render: (text: string, record: any) => {
                if (!text) return null;

                // 只显示类名，不显示包路径
                const className = text.split('.').pop() || text;

                // 构建跳转链接：直接使用xmlFilePath的相对路径
                let gitLink = null;
                if (unitInfo?.gitRepoUrl && record.xmlFilePath) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';

                    // 直接使用xmlFilePath的相对路径（已经去掉了代码仓根目录）
                    const xmlRelativePath = formatRelativePathUtil(record.xmlFilePath, unitInfo?.unitId);

                    gitLink = buildFileLink(unitInfo.gitRepoUrl, xmlRelativePath, branch);
                }

                if (gitLink) {
                    return (
                        <a
                            href={gitLink}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{
                                fontWeight: 600,
                                color: '#1890ff',
                                fontSize: '13px'
                            }}
                            title={`点击查看 ${text}`}
                        >
                            {className}
                        </a>
                    );
                }

                return (
                    <span
                        style={{
                            fontWeight: 600,
                            color: '#1e293b',
                            fontSize: '13px'
                        }}
                        title={text}
                    >
                        {className}
                    </span>
                );
            }
        },
        {
            title: '方法',
            dataIndex: 'mapperMethodName',
            key: 'mapperMethodName',
            width: 200,
            render: (text: string, record: any) => {
                if (!text) return null;

                // 对于XML类型，不显示跳转链接（因为methodStartLine是XML行号，不是Java方法行号）
                // 只对注解类型显示跳转链接
                const isAnnotation = record.sourceType === 'MYBATIS_ANNOTATION';

                let gitLink = null;
                if (isAnnotation && unitInfo?.gitRepoUrl && record.mapperClassName && record.methodStartLine) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
                    const javaPath = `src/main/java/${record.mapperClassName.replace(/\./g, '/')}.java`;
                    gitLink = buildFileLink(unitInfo.gitRepoUrl, javaPath, branch, record.methodStartLine, record.methodEndLine);
                }

                if (gitLink) {
                    return (
                        <span>
                            <a
                                href={gitLink}
                                target="_blank"
                                rel="noopener noreferrer"
                                style={{ fontSize: '13px', color: '#1890ff' }}
                                title={`点击跳转到 ${text}`}
                            >
                                {text}
                            </a>
                            {record.methodStartLine && (
                                <span style={{
                                    marginLeft: '6px',
                                    color: '#52c41a',
                                    fontFamily: 'monospace',
                                    fontSize: '11px'
                                }}>
                                    L{record.methodStartLine}
                                </span>
                            )}
                        </span>
                    );
                }

                // 对于XML类型，只显示方法名，不显示行号
                return (
                    <span style={{ fontSize: '13px', color: '#262626' }} title={text}>
                        {text}
                    </span>
                );
            }
        },
        {
            title: 'XML',
            dataIndex: 'xmlFilePath',
            key: 'xmlFilePath',
            width: 300,
            ellipsis: true,
            render: (text: string, record: any) => {
                // 如果是注解来源，不显示XML路径
                if (record.sourceType === 'MYBATIS_ANNOTATION') {
                    return null;
                }

                if (!text) return null;

                // 提取仓库名称（从gitRepoUrl或unitId）
                let repoName = unitInfo?.unitId;
                if (unitInfo?.gitRepoUrl) {
                    const urlParts = unitInfo.gitRepoUrl.split('/');
                    const lastPart = urlParts[urlParts.length - 1];
                    repoName = lastPart.replace(/\.git$/i, '');
                }

                // 格式化为相对路径
                const relativePath = formatRelativePathUtil(text, repoName);

                // 构建XML文件跳转链接（使用methodStartLine作为XML行号）
                let gitLink = null;
                if (unitInfo?.gitRepoUrl && record.methodStartLine) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
                    gitLink = buildFileLink(unitInfo.gitRepoUrl, relativePath, branch, record.methodStartLine);
                } else if (unitInfo?.gitRepoUrl) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
                    gitLink = buildFileLink(unitInfo.gitRepoUrl, relativePath, branch);
                }

                if (gitLink) {
                    return (
                        <span>
                            <a
                                href={gitLink}
                                target="_blank"
                                rel="noopener noreferrer"
                                style={{ color: '#1890ff', fontSize: '12px' }}
                                title={`点击查看 ${relativePath}`}
                            >
                                {relativePath}
                            </a>
                            {record.methodStartLine && (
                                <span style={{
                                    marginLeft: '6px',
                                    color: '#52c41a',
                                    fontFamily: 'monospace',
                                    fontSize: '11px'
                                }}>
                                    L{record.methodStartLine}
                                </span>
                            )}
                        </span>
                    );
                }

                return (
                    <span style={{ color: '#475569', fontSize: '12px' }} title={relativePath}>
                        {relativePath}
                        {record.methodStartLine && (
                            <span style={{
                                marginLeft: '6px',
                                color: '#52c41a',
                                fontFamily: 'monospace',
                                fontSize: '11px'
                            }}>
                                L{record.methodStartLine}
                            </span>
                        )}
                    </span>
                );
            }
        }
    ];

    const handleTableChange = (pager: TablePaginationConfig) => {
        setPagination(pager);
        loadPage(pager.current as number, pager.pageSize as number);
    };

    // 查看表的调用拓扑
    const handleViewTableTopology = async (table: string) => {
        setCurrentTableName(table);
        setCallGraphModalVisible(true);
        setCallGraphLoading(true);

        try {
            const res: any = await queryCallGraph({
                unitId: unitId,
                target: table,
                queryType: 'TABLE',
                depth: 5,
                includeUpstream: true,
                includeDownstream: false
            });
            setCallGraphData(res?.data || res);
        } catch (e: any) {
            message.error(e?.message || '查询表调用拓扑失败');
            setCallGraphData(null);
        } finally {
            setCallGraphLoading(false);
        }
    };



    // 分组视图的列配置（不包含表名列，调整列宽）
    const groupColumns: any[] = [
        {
            title: '操作',
            dataIndex: 'operationType',
            key: 'operationType',
            width: 100,
            fixed: true,
            render: (text: string, record: any) => {
                const operation = (text || record.operation || '').toUpperCase();
                if (!operation) return <span>-</span>;

                const operationColorMap: Record<string, string> = {
                    'SELECT': '#1890ff',
                    'INSERT': '#52c41a',
                    'UPDATE': '#faad14',
                    'DELETE': '#ff4d4f'
                };

                const color = operationColorMap[operation] || '#8c8c8c';

                return (
                    <Tag color={color} style={{ margin: 0, fontWeight: 600 }}>
                        {operation}
                    </Tag>
                );
            }
        },
        {
            title: '来源',
            dataIndex: 'sourceType',
            key: 'sourceType',
            width: 100,
            fixed: true,
            render: (text: string) => {
                if (!text) return <span>-</span>;

                const sourceTypeMap: Record<string, { label: string; color: string }> = {
                    'MYBATIS_XML': { label: 'XML', color: '#1890ff' },
                    'MYBATIS_ANNOTATION': { label: '注解', color: '#722ed1' },
                    'JPA': { label: 'JPA', color: '#faad14' },
                    'NATIVE': { label: '原生', color: '#13c2c2' }
                };

                const config = sourceTypeMap[text] || { label: text.toUpperCase(), color: '#8c8c8c' };

                return (
                    <Tag color={config.color} style={{ margin: 0 }}>
                        {config.label.toUpperCase()}
                    </Tag>
                );
            }
        },
        {
            title: '包名',
            dataIndex: 'mapperClassName',
            key: 'packageName',
            width: 200,
            fixed: true,
            render: (text: string) => {
                if (!text) return <span>-</span>;

                const parts = text.split('.');
                if (parts.length <= 1) return <span>-</span>;

                const packageName = parts.slice(0, -1).join('.');

                return (
                    <span
                        style={{
                            fontSize: '12px',
                            color: '#8c8c8c',
                            fontFamily: 'Consolas, Monaco, monospace'
                        }}
                        title={packageName}
                    >
                        {packageName}
                    </span>
                );
            }
        },
        {
            title: '类',
            dataIndex: 'mapperClassName',
            key: 'mapperClassName',
            width: 150,
            fixed: true,
            render: (text: string, record: any) => {
                if (!text) return <span>-</span>;

                const className = text.split('.').pop() || text;

                // 构建跳转链接：直接使用xmlFilePath的相对路径
                let gitLink = null;
                if (unitInfo?.gitRepoUrl && record.xmlFilePath) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';

                    // 直接使用xmlFilePath的相对路径（已经去掉了代码仓根目录）
                    const xmlRelativePath = formatRelativePathUtil(record.xmlFilePath, unitInfo?.unitId);

                    gitLink = buildFileLink(unitInfo.gitRepoUrl, xmlRelativePath, branch);
                }

                if (gitLink) {
                    return (
                        <a
                            href={gitLink}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{
                                fontWeight: 600,
                                color: '#1890ff',
                                fontSize: '13px'
                            }}
                            title={`点击查看 ${text}`}
                        >
                            {className}
                        </a>
                    );
                }

                return (
                    <span
                        style={{
                            fontWeight: 600,
                            color: '#1e293b',
                            fontSize: '13px'
                        }}
                        title={text}
                    >
                        {className}
                    </span>
                );
            }
        },
        {
            title: '方法',
            dataIndex: 'mapperMethodName',
            key: 'mapperMethodName',
            width: 180,
            fixed: true,
            render: (text: string, record: any) => {
                if (!text) return <span>-</span>;

                // 对于XML类型，不显示跳转链接（因为methodStartLine是XML行号，不是Java方法行号）
                // 只对注解类型显示跳转链接
                const isAnnotation = record.sourceType === 'MYBATIS_ANNOTATION';

                let gitLink = null;
                if (isAnnotation && unitInfo?.gitRepoUrl && record.mapperClassName && record.methodStartLine) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
                    const javaPath = `src/main/java/${record.mapperClassName.replace(/\./g, '/')}.java`;
                    gitLink = buildFileLink(unitInfo.gitRepoUrl, javaPath, branch, record.methodStartLine, record.methodEndLine);
                }

                if (gitLink) {
                    return (
                        <span>
                            <a
                                href={gitLink}
                                target="_blank"
                                rel="noopener noreferrer"
                                style={{ fontSize: '13px', color: '#1890ff' }}
                                title={`点击跳转到 ${text}`}
                            >
                                {text}
                            </a>
                            {record.methodStartLine && (
                                <span style={{
                                    marginLeft: '6px',
                                    color: '#52c41a',
                                    fontFamily: 'monospace',
                                    fontSize: '11px'
                                }}>
                                    L{record.methodStartLine}
                                </span>
                            )}
                        </span>
                    );
                }

                // 对于XML类型，只显示方法名，不显示行号
                return (
                    <span style={{ fontSize: '13px', color: '#262626' }} title={text}>
                        {text}
                    </span>
                );
            }
        },
        {
            title: 'XML',
            dataIndex: 'xmlFilePath',
            key: 'xmlFilePath',
            width: 250,
            fixed: true,
            render: (text: string, record: any) => {
                if (record.sourceType === 'MYBATIS_ANNOTATION') {
                    return <span style={{ color: '#8c8c8c', fontSize: '12px' }}>-</span>;
                }

                if (!text) return <span>-</span>;

                // 提取仓库名称（从gitRepoUrl或unitId）
                let repoName = unitInfo?.unitId;
                if (unitInfo?.gitRepoUrl) {
                    const urlParts = unitInfo.gitRepoUrl.split('/');
                    const lastPart = urlParts[urlParts.length - 1];
                    repoName = lastPart.replace(/\.git$/i, '');
                }

                const relativePath = formatRelativePathUtil(text, repoName);

                // 构建XML文件跳转链接（使用methodStartLine作为XML行号）
                let gitLink = null;
                if (unitInfo?.gitRepoUrl && record.methodStartLine) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
                    gitLink = buildFileLink(unitInfo.gitRepoUrl, relativePath, branch, record.methodStartLine);
                } else if (unitInfo?.gitRepoUrl) {
                    const branch = unitInfo.currentBranch || unitInfo.defaultBranch || 'master';
                    gitLink = buildFileLink(unitInfo.gitRepoUrl, relativePath, branch);
                }

                if (gitLink) {
                    return (
                        <span>
                            <a
                                href={gitLink}
                                target="_blank"
                                rel="noopener noreferrer"
                                style={{ color: '#1890ff', fontSize: '12px' }}
                                title={`点击查看 ${relativePath}`}
                            >
                                {relativePath}
                            </a>
                            {record.methodStartLine && (
                                <span style={{
                                    marginLeft: '6px',
                                    color: '#52c41a',
                                    fontFamily: 'monospace',
                                    fontSize: '11px'
                                }}>
                                    L{record.methodStartLine}
                                </span>
                            )}
                        </span>
                    );
                }

                return (
                    <span style={{ color: '#475569', fontSize: '12px' }} title={relativePath}>
                        {relativePath}
                        {record.methodStartLine && (
                            <span style={{
                                marginLeft: '6px',
                                color: '#52c41a',
                                fontFamily: 'monospace',
                                fontSize: '11px'
                            }}>
                                L{record.methodStartLine}
                            </span>
                        )}
                    </span>
                );
            }
        }
    ];



    // 外层表格列定义
    const outerColumns: any[] = [
        {
            title: '表名',
            dataIndex: 'tableName',
            key: 'tableName',
            width: 250,
            render: (text: string) => (
                <span style={{ fontWeight: 600, fontSize: 14 }}>{text}</span>
            )
        },
        {
            title: '操作类型',
            dataIndex: 'operationTypes',
            key: 'operationTypes',
            width: 300,
            render: (types: string[]) => (
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                    {types.map(type => (
                        <Tag key={type} color={
                            type === 'SELECT' || type === 'select' ? 'blue' :
                                type === 'INSERT' || type === 'insert' ? 'green' :
                                    type === 'UPDATE' || type === 'update' ? 'orange' :
                                        type === 'DELETE' || type === 'delete' ? 'red' : 'default'
                        }>
                            {String(type).toUpperCase()}
                        </Tag>
                    ))}
                </div>
            )
        },
        {
            title: '操作数量',
            dataIndex: 'operationCount',
            key: 'operationCount',
            width: 120,
            render: (count: number) => (
                <span style={{ fontWeight: 500 }}>{count}</span>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 120,
            render: (_: any, record: any) => (
                <Button
                    type="link"
                    size="small"
                    icon={<ShareAltOutlined />}
                    onClick={(e) => {
                        e.stopPropagation();
                        handleViewTableTopology(record.tableName);
                    }}
                >
                    查看拓扑
                </Button>
            )
        }
    ];

    // 渲染分组视图（优化版：按需加载）
    const renderGroupedView = () => {
        if (groupData.length === 0) {
            return <Empty description="暂无数据" />;
        }

        return (
            <Table
                rowKey="tableName"
                columns={outerColumns}
                dataSource={groupData}
                loading={groupLoading}
                pagination={{
                    current: groupCurrentPage,
                    pageSize: groupPageSize,
                    total: groupTotal,
                    onChange: (page, pageSize) => {
                        if (pageSize !== groupPageSize) {
                            setGroupPageSize(pageSize);
                            loadGroupData(1, pageSize);
                        } else {
                            setGroupCurrentPage(page);
                            loadGroupData(page, pageSize);
                        }
                    },
                    showSizeChanger: true,
                    showTotal: (total) => `共 ${total} 个表`,
                    pageSizeOptions: ['5', '10', '20', '50']
                }}
                expandable={{
                    expandedRowKeys: expandedRowKeys,
                    onExpand: (expanded, record) => {
                        if (expanded) {
                            // 展开时加载数据
                            loadTableOperations(record.tableName);
                            setExpandedRowKeys([...expandedRowKeys, record.tableName]);
                        } else {
                            // 收起时移除
                            setExpandedRowKeys(expandedRowKeys.filter(key => key !== record.tableName));
                        }
                    },
                    expandedRowRender: (record) => {
                        const operations = expandedDataCache[record.tableName] || [];
                        return (
                            <Table
                                rowKey="id"
                                columns={groupColumns}
                                dataSource={operations}
                                pagination={false}
                                loading={!expandedDataCache[record.tableName]}
                                size="small"
                                style={{ margin: 0 }}
                            />
                        );
                    }
                }}
            />
        );
    };

    return (
        <>
            <div style={{ padding: 12 }}>
                <div style={{
                    marginBottom: 12,
                    display: 'flex',
                    gap: 8,
                    alignItems: 'center',
                    flexWrap: 'wrap'
                }}>
                    <Radio.Group
                        value={viewMode}
                        onChange={(e) => setViewMode(e.target.value)}
                        buttonStyle="solid"
                        style={{ marginRight: 8 }}
                    >
                        <Radio.Button value="group">表视图</Radio.Button>
                        <Radio.Button value="table">操作视图</Radio.Button>
                    </Radio.Group>
                    <Input.Search
                        allowClear
                        placeholder="搜索表名/类名/方法名"
                        value={keyword}
                        onChange={(e) => setKeyword(e.target.value)}
                        onSearch={onSearch}
                        style={{ width: 280 }}
                    />
                    <Select
                        allowClear
                        placeholder="操作类型"
                        value={operationType}
                        onChange={(v) => {
                            setOperationType(v);
                            if (viewMode === 'table') {
                                loadPage(1, pagination.pageSize);
                            } else {
                                loadGroupData(1, groupPageSize);
                            }
                        }}
                        style={{ width: 140 }}
                        options={[
                            { label: 'SELECT', value: 'select' },
                            { label: 'INSERT', value: 'insert' },
                            { label: 'UPDATE', value: 'update' },
                            { label: 'DELETE', value: 'delete' }
                        ]}
                    />
                </div>

                {viewMode === 'table' ? (
                    <Table
                        rowKey="id"
                        loading={loading}
                        columns={columns}
                        dataSource={records}
                        pagination={pagination}
                        onChange={handleTableChange}
                        tableLayout="fixed"
                        scroll={{ x: 'max-content' }}
                    />
                ) : (
                    <Spin spinning={loading}>
                        {renderGroupedView()}
                    </Spin>
                )}
            </div>

            <Modal
                title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <ShareAltOutlined />
                        <span>表调用拓扑</span>
                    </div>
                }
                open={callGraphModalVisible}
                onCancel={() => {
                    setCallGraphModalVisible(false);
                    setCallGraphData(null);
                    setCurrentTableName('');
                }}
                footer={null}
                width="90%"
                style={{ top: 20 }}
                styles={{ body: { height: 'calc(100vh - 200px)', overflow: 'auto' } }}
            >
                <div className="topology-info">
                    <div>
                        <span className="label">目标表：</span>
                        <span className="value">{currentTableName}</span>
                    </div>
                </div>
                {callGraphData ? (
                    <CallGraphViewer data={callGraphData} loading={callGraphLoading} />
                ) : (
                    <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
                        {callGraphLoading ? '加载中...' : '暂无调用拓扑数据'}
                    </div>
                )}
            </Modal>
        </>
    );
};

export default DatabaseAnalysis;
